package com.taomus.mytools.crypto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;

public class CryptoHelper {
	public static String SHA1(String value){
		return encode("sha1",value);
	}
	public static String MD5(String value){
		return encode("md5",value);
	}
	/**
	 * MD5 and SHA1
	 * @param type
	 * @param value
	 * @return
	 */
	private static String encode(String type,String value){
		try {
			char[] hexDigits ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
			MessageDigest md = MessageDigest.getInstance(type);
			byte[] digest = md.digest(value.getBytes());
			int count = digest.length;
			char[] res = new char[count*2];
			for(int i=0,k=0;i<count;i++){
				byte b0 = digest[i];
				res[k++] = hexDigits[b0 >> 4 & 0xf];
				res[k++] = hexDigits[b0 & 0xf];
			}
			return new String(res);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String DESEncrypt(String pwd,String value){
		return CrypotDES.encrypt(pwd, value);
	}
	
	public static String DESDecrypt(String pwd,String value){
		return CrypotDES.decrypt(pwd, value);
	}
	
	public static byte[] base64Encode(byte[] binaryData){
		return Base64.encodeBase64(binaryData);
	}
	
	public static byte[] base64Decode(byte[] base64Data){
		return Base64.decodeBase64(base64Data);
	}
	
	public static String URLEncode(String str) throws EncoderException{
		return new URLCodec().encode(str);
	}
	public static String URLDecode(String str) throws DecoderException{
		return new URLCodec().decode(str);
	}
}
